<template>
  <div class="km_container basic_info km_box">
    <div class="km_search">
      <el-popover placement="bottom" trigger="hover">
        <span class="el-dropdown-link" slot="reference">
          <i class="icon iconfont icon-zhishikujiansuo1"></i><i class="el-icon-arrow-down el-icon--right"></i>
        </span>
        <div style="max-height: 400px; overflow-y: auto">
          <div class="topNav clearfix">
            <div @click="insideKm" class="km_breadcrumb" :class="isChoose ? 'crumb-active' : 'crumb-move'">
              {{ $t('km.kmInside') }}
            </div>
            <div class="km_breadcrumb">|</div>
            <div @click="outKm" class="km_breadcrumb" :class="!isChoose ? 'crumb-active' : 'crumb-move'">
              {{ $t('km.kmOutside') }}
            </div>
          </div>
          <div class="tree_container">
            <kmTree
              :KmType="KmType"
              :type="'webchat'"
              :manage="1"
              @childId="childId"
              treeHeight="300px"
              ref="kmTree"
            ></kmTree>
          </div>
        </div>
      </el-popover>
      <!-- v22.2 辅助坐席知识库支持排序 start -->
      <el-popover placement="bottom" trigger="hover">
        <span class="el-dropdown-link" slot="reference">
          <i class="icon iconfont icon-paixu"></i>
          <span style="color: #333; padding: 0px 5px">{{ $t('km.cataSort') }}</span>
        </span>
        <el-radio-group v-model="sortType" @change="sortClick">
          <el-radio style="margin-bottom: 8px" label="">{{ $t('km.searchbyScore') }}</el-radio
          ><br />
          <el-radio style="margin-bottom: 8px" label="hits">{{ $t('km.searchbyHits') }}</el-radio
          ><br />
          <el-radio label="lastTime">{{ $t('km.searchbyLastTime') }}</el-radio>
        </el-radio-group>
      </el-popover>
      <!-- v22.2 辅助坐席知识库支持排序 end -->
      <div style="width: 100%">
        <el-input size="mini" v-model.trim="kmSearchContent" @keyup.native.enter.stop="handlerClick">
          <i class="el-input__icon el-icon-search" slot="suffix" @click="handlerClick"> </i>
        </el-input>
      </div>
    </div>
    <div class="km_search_result">
      <div class="result">
        <p
          v-html="catasearch ? $t('webchat.totalKmResult', { result, outResult, innerResult }) : kmcata"
          class="greyFont"
        ></p>

        <typeSelect @change="queryModelChange"></typeSelect>
        <p
          v-text="resultList.length <= 0 && currentAction === 'queryItemList' ? $t('webchat.noData') : ''"
          class="greyFont"
          style="line-height: 4; text-align: center"
        ></p>
        <div
          v-for="(item, index) in resultList"
          :key="index"
          class="result_list"
          v-on:mouseover="mouseOverList($event)"
          v-on:mouseout="mouseOutList($event)"
        >
          <div class="kmtitle clearfix">
            <h4 v-html="item.title"></h4>
            <span v-text="item.kmType === 'inner' ? $t('webchat.inner') : $t('webchat.out')" class="km-type"></span>
            <div class="operate">
              <span @click.stop="preview(item)" v-if="handle.includes('preview')">{{ $t('km.preview') }}</span>
              <span @click.stop="sendKmContent('send', item)" v-if="handle.includes('send')">{{ $t('sms.send') }}</span>
              <span @click.stop="sendKmContent('use', item)" v-if="handle.includes('use')">{{
                $t('webchat.use')
              }}</span>
              <span @click.stop="copy(item.content || item.contentTxt)" v-if="handle.includes('copy')">{{
                $t('public.copy')
              }}</span>
            </div>
            <div
              class="km_baseinfo_preview"
              v-show="item.isShowKmPreview"
              :class="{
                kmlayout: item.isShowKmPreview,
                kmlayin: !item.isShowKmPreview
              }"
            >
              <div class="km_preview_title">
                <span class="titleText">{{ $t('km.preview') }}</span>
                <span @click.stop="sendKmContent('send', item)" class="useBtn" v-if="handle.includes('send')">{{
                  $t('sms.send')
                }}</span>
                <span
                  @click.stop="sendKmContent('use', item)"
                  class="useBtn"
                  style="right: 60px"
                  v-if="handle.includes('use')"
                  >{{ $t('webchat.use') }}</span
                >
                <span
                  @click.stop="copy(previewContent)"
                  v-if="handle.includes('copy')"
                  class="useBtn"
                  style="right: 60px"
                  >{{ $t('public.copy') }}</span
                >
                <span class="el-icon-close" @click="closeKmPreview(item)"></span>
              </div>
              <div class="km_preview_content" style="margin: 20px">
                <p v-html="previewTitle" class="titleText contentTitle"></p>
                <div v-html="previewContent" class="editor-preview" @click="aClickFun"></div>
                <knowledgeLabel
                  v-if="item.isShowKmPreview"
                  :tagList="item.tagList || []"
                  :isPreview="true"
                ></knowledgeLabel>
              </div>
            </div>
          </div>
          <div class="kmcontent km-text-hide" v-html="item.content ? item.content : item.contentTxt"></div>
          <div
            class="kmcontent km-text-limit"
            style="-webkit-box-orient: vertical"
            v-html="item.content ? item.content : item.contentTxt"
          ></div>
          <div class="open-text" @click="changeFoldedStatus($event)" ds_attr="unfolded">
            {{ $t('email.unfolded') }}
          </div>
        </div>
        <div v-show="loading" class="loading-footer">
          <div class="loader">
            <div class="loading-1">
              <i></i>
              <i></i>
              <i></i>
            </div>
          </div>
        </div>
        <!--<div class="btn" v-show="!noMore && (result > 10)" @click.stop="loadMore"><i class="iconfont icon-shuaxin"><span>{{$t('public.loadMore')}}</span></i></div>-->
        <div class="btn-group">
          <el-button
            type="primary"
            v-show="!noMore && result > 10"
            class="btn primary_btn"
            @click.stop="loadMore"
            size="small"
            >{{ $t('public.loadMore') }}</el-button
          >
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import kmTree from '@/components/business-modules/km/km-search/KmTree.vue'
import { deepClone, filterXSS } from '@/utils/m7Utils'
import Clipboard from 'clipboard-js'
import bus from '@/store/eventBus'
import send from '@/store/api/http'
import typeSelect from './typeSelect.vue'
import knowledgeLabel from '@/components/business-modules/km/km-detail/knowledgeLabel.vue'
export default {
  name: 'kmSearch',
  props: {
    // 可操作类型
    handle: {
      type: Array,
      default: function () {
        return ['preview', 'use', 'send']
      }
    },
    type: { type: String, default: '' }
  },
  data() {
    return {
      result: 0,
      visible: false,
      innerResult: 0,
      outResult: 0,
      isChoose: true,
      KmType: 'inner',
      sortType: '',
      kmSearchContent: '',
      page: 1,
      resultList: [],
      catasearch: true,
      kmcata: '',
      //        isShowKmPreview: false, // 知识库预览弹窗
      previewContent: '', // 预览内容
      previewTitle: '', // 预览标题
      noMore: false, // 是否滚动加载更多
      loading: false,
      currentAction: '', // 当前发送的请求
      currentCid: '',
      list: [],
      refreshTree: 0,
      queryModel: 'all',
      searchinprogress: false //搜索是否进行中
    }
  },
  watch: {
    '$store.state.call.participleCon': function (content) {
      if (content) {
        this.kmSearchContent = content
        this.handlerClick()
      }
    }
  },
  methods: {
    queryModelChange(value) {
      this.queryModel = value
      this.search()
    },
    copy(content) {
      Clipboard.copy(content).then(() => {
        this.$message.success(this.$t('config.business.copySuccess'))
      })
    },
    mouseOverList(event) {
      let pane = event.currentTarget
      if (pane) {
        let node = pane.getElementsByClassName('km-text-hide')[0]
        let child = pane.getElementsByClassName('open-text')[0]
        if (node.offsetHeight > 51) {
          // 大于3行时加上展开2字
          child.style.display = 'block'
        } else {
          child.style.display = 'none'
        }
      }
    },
    mouseOutList(event) {
      let pane = event.currentTarget
      if (pane) {
        let child = pane.getElementsByClassName('open-text')[0]
        child.style.display = 'none'
      }
    },
    handlerClick() {
      if (this.kmSearchContent) {
        this.$store.commit('call/SET_PARTICIPLE_CON', '')
        this.search()
      } else {
        this.$message.error(this.$t('webchat.searchConNoEmpty'))
        return
      }
    },
    // v22.2 辅助座席支持排序
    sortClick() {
      if (this.currentAction === 'queryItemList') {
        this.childId(this.currentCid)
      } else {
        this.$store.commit('call/SET_PARTICIPLE_CON', '')
        this.search()
      }
    },
    aClickFun(e) {
      e.preventDefault()
      this.$nextTick(() => {
        if (e.target.nodeName.toLowerCase() === 'a') {
          let dom = e.target
          let domUrl = dom.getAttribute('href')
          try {
            window.open(domUrl, '_blank')
          } catch (e) {
            this.$message.error(this.$t('webchat.urlError'))
          }
        }
      })
    },
    search(page, isScroll) {
      // 表单搜索
      if (this.searchinprogress) {
        return
      }
      this.searchinprogress = true
      this.currentAction = 'queryKmDic'
      if (!isScroll) {
        // 不是点击加载更多的时候，要重置
        this.resultList = []
        this.page = 1
      }
      if (page == null) {
        page = this.page
      }
      let data = {
        key: this.kmSearchContent,
        page: page,
        kmType: this.KmType,
        queryModel: this.queryModel,
        onlyQueryValid: true
      }
      data.kmType = 'inner,outer'
      // v22.2 辅助坐席知识库支持排序 start
      if (['hits', 'lastTime'].includes(this.sortType)) {
        data.sortType = this.sortType
      }
      this.catasearch = true
      this.loading = true
      this.$store.dispatch('queryKmDic', data).then((rep) => {
        this.loading = false
        if (rep && rep.success) {
          let list = this.$store.state.km.kmDic.list || []
          this.list = deepClone(list)
          this.result = rep.count || 0
          if (this.list.length < 10) {
            this.noMore = true
          } else {
            this.noMore = false
          }
          this.innerResult = rep.innerCount || 0
          this.outResult = rep.outerCount || 0
          for (let k = 0; k < this.list.length; k++) {
            let _id = this.list[k].cid
            this.resultList.push({
              titleText: this.list[k].titleText || '',
              kmcontent_id: this.list[k]._id,
              _id: _id,
              isShowKmPreview: false,
              title: filterXSS(this.list[k].title),
              content: filterXSS(this.list[k].content),
              kmType: this.list[k].kmType,
              contentTxt: this.list[k].contentTxt,
              tagList: this.list[k].tagList || []
            })
          }
        } else {
          this.list = []
          this.resultList = []
        }
        this.searchinprogress = false
      })
    },
    searchInnerKmList() {
      this.isChoose = true
      this.KmType = 'inner'
      this.$refs.kmTree.fetchData('inner')
      this.childId('0')
    },
    globalKmShow() {
      this.resultList.forEach((item) => {
        this.$set(item, 'isShowKmPreview', false)
      })
    },
    preview(val) {
      // 预览
      this.resultList.forEach((item) => {
        // 当前点击置为true 其他全置为false, 避免覆盖现象
        if (val === item) {
          this.$set(val, 'isShowKmPreview', true)
        } else {
          this.$set(item, 'isShowKmPreview', false)
        }
      })
      let data = {
        _id: val.kmcontent_id,
        kmType: val.kmType
      }
      let previewData = {}
      this.previewTitle = val.title
      this.$store.dispatch('showItemEdit', data).then(() => {
        // 获取每条知识库内容
        previewData = this.$store.state.km.ItemEditdata
        if (previewData.success) {
          this.previewContent = filterXSS(previewData.row.content, true)
        } else {
          window.setTimeout(() => {
            val.isShowKmPreview = false
          }, 400)
        }
      })
    },
    closeKmPreview(val) {
      // 关闭预览弹窗
      this.$set(val, 'isShowKmPreview', false)
      this.previewTitle = ''
      this.previewContent = ''
    },
    childId(cid, isScroll) {
      // 目录搜索
      this.currentAction = 'queryItemList'
      // this.kmSearchContent = ''
      if (!isScroll) {
        // 不是滚动加载的时候，要重置
        this.resultList = []
        this.page = 1
      }
      this.currentCid = cid
      this.loading = true
      //        if (cid === '0') { // 点击目录预览时
      //          let data = {
      //            kmType: this.KmType,
      //            type: 'im',
      //            flag: true,
      //            cid: 'all'
      //          }
      //          debugger
      //          this.$store.dispatch('queryItemList', data).then((resp) => {
      //            this.loading = false
      //            if (resp && resp.success) {
      //              this.catasearch = false
      //              this.list = resp.list || []
      //              this.result = resp.count || 0
      //              this.noMore = true // 因为只取最新的10条
      //              if (this.KmType === 'inner') {
      //                this.innerResult = resp.count || 0
      //                this.outResult = 0
      //              } else {
      //                this.innerResult = 0
      //                this.outResult = resp.count || 0
      //              }
      //            } else {
      //              this.list = []
      //              this.resultList = []
      //            }
      //            this.getKmCata(cid)
      //          })
      //        } else {
      if (cid === '0') {
        cid = 'all'
      }
      let data = {
        cid: cid,
        kmType: this.KmType,
        page: this.page || 1,
        type: 'im',
        sortType: this.sortType,
        sortDirection: -1,
        onlyQueryValid: true
      }
      this.$store.dispatch('queryItemList', data).then((resp) => {
        this.loading = false
        if (resp && resp.success) {
          this.catasearch = false
          this.list = resp.list || []
          this.result = resp.count || 0
          if (this.list.length < 10) {
            this.noMore = true
          } else {
            this.noMore = false
          }
          if (this.KmType === 'inner') {
            this.innerResult = resp.count || 0
            this.outResult = 0
          } else {
            this.innerResult = 0
            this.outResult = resp.count || 0
          }
        } else {
          this.list = []
          this.resultList = []
        }
        this.getKmCata(cid)
        if (this.kmSearchContent) {
          this.handlerClick()
        }
      })
      //        }
    },
    getKmCata(cid) {
      // 获取目录路径
      let _id = cid
      for (let k = 0; k < this.list.length; k++) {
        this.resultList.push({
          titleText: this.list[k].titleText || '',
          kmcontent_id: this.list[k]._id,
          _id: _id,
          title: filterXSS(this.list[k].title),
          content: filterXSS(this.list[k].content),
          kmType: this.list[k].kmType,
          contentTxt: this.list[k].contentTxt,
          tagList: this.list[k].tagList || []
        })
      }
      this.kmcata = this.$t('km.mulu1')
      let catalogTree = this.$store.state.km.webchatTree
      for (let i = 0; i < catalogTree.length; i++) {
        let catalog = catalogTree[i]
        if (catalog._id === _id) {
          this.kmcata = this.$t('km.mulu') + catalog.name
          break
        } else {
          let childs1 = catalog.childs
          for (let j = 0; j < childs1.length; j++) {
            let child1 = childs1[j]
            if (child1._id === _id) {
              this.kmcata = this.$t('km.mulu') + catalog.name + ' > ' + child1.name
              break
            } else {
              let childs2 = child1.childs
              for (let m = 0; m < childs2.length; m++) {
                let child2 = childs2[m]
                if (child2._id === _id) {
                  this.kmcata = this.$t('km.mulu') + catalog.name + ' > ' + child1.name + ' > ' + child2.name
                  break
                } else {
                }
              }
            }
          }
        }
      }
    },
    //      处理滚动条滚到底部加载数据
    loadMore() {
      if (!this.noMore) {
        this.resultList.forEach((item) => {
          item.isShowKmPreview = false
        })
        this.page += 1
        if (this.currentAction === 'queryItemList') {
          this.childId(this.currentCid, true)
        } else {
          if (this.kmSearchContent) {
            this.search(this.page, true)
          } else {
            this.$message.error(this.$t('webchat.searchConNoEmpty'))
            return
          }
        }
      }
    },
    outKm() {
      window._hmt && window._hmt.push(['_trackEvent', '在线咨询', 'PM-外部知识库'])
      this.isChoose = false
      this.KmType = 'outer'
      this.$refs.kmTree.fetchData('outer')
      this.childId('0')
    },
    insideKm() {
      window._hmt && window._hmt.push(['_trackEvent', '在线咨询', 'PM-内部知识库'])
      this.isChoose = true
      this.KmType = 'inner'
      this.$refs.kmTree.fetchData('inner')
      this.childId('0')
    },
    changeFoldedStatus(event) {
      // 更改展开还是收起的状态
      let pane = event.currentTarget
      if (pane) {
        let flag = pane.getAttribute('ds_attr')
        let child = pane.previousSibling
        if (flag === 'unfolded') {
          child.style.display = 'block'
          pane.setAttribute('ds_attr', 'folded')
          pane.innerHTML = this.$t('email.folded')
        } else {
          child.style.display = '-webkit-box'
          pane.setAttribute('ds_attr', 'unfolded')
          pane.innerHTML = this.$t('email.unfolded')
        }
      }
    },
    sendKmContent(type, item) {
      // this.$emit('sendKmContent', type, contentTxt, content)
      if (type === 'send') {
        window._hmt && window._hmt.push(['_trackEvent', '在线咨询', 'PM-发送知识库'])
        item.isShowKmPreview = false
      }
      if (type === 'use') {
        window._hmt && window._hmt.push(['_trackEvent', '在线咨询', 'PM-使用知识库'])
      }
      bus.$emit('sendKmContent', type, item)
    },
    // v22.2 辅助坐席知识库保存排序方式
    async getSortConfig() {
      let req = {
        data: {},
        action: 'app.km.getUserSortType'
      }
      let data = await send.fetch(req, 'post', true)
      if (data.success && data.data) {
        this.sortType = data.data.sortType || ''
      }
    },
    setKmSearchContent(value) {
      this.kmSearchContent = value
      if (value) {
        this.search()
      }
    }
  },
  components: {
    kmTree,
    typeSelect,
    knowledgeLabel
  },
  // v22.2 辅助坐席知识库保存排序方式
  async mounted() {
    await this.getSortConfig()
    if (this.type !== 'global') {
      bus.$on('fastSearchKm', (data) => {
        this.kmSearchContent = data.data
        if (data.data) {
          this.search()
        }
      })
    } else {
      this.insideKm()
    }
  },
  beforeDestroy() {
    if (this.type !== 'global') {
      bus.$off('fastSearchKm')
    }
  }
}
</script>
<style lang="stylus" scoped>
@import "../../../assets/common.styl";
.km_search
  display flex
  align-items center
  padding-bottom 10px
  border-bottom 1px solid $cf-gray5
  color #ccc
  .el-dropdown-link
    display inline-block
    padding 5px
    border-radius 4px
    border 1px solid #fff
    margin 0px 5px
    align-items center
    white-space nowrap
    cursor pointer
    &:hover
      border-color $c-main
      background-color #f5fffe
    i
      color $cf-gray5
      font-weight bold
.topNav
  display flex
  align-items center
  justify-content center
  font-size 14px
  color $cf-gray5
  width 250px
  padding-bottom 10px
  .km_breadcrumb
    float left
    padding 0 10px
    cursor pointer
    &:hover, &:active
      color $c-main
  .crumb-active
    color $c-main
  .crumb-move
    color $cf-gray0
.tree_container
  width 250px
  margin-top -20px
.km_search_result
  padding 10px 0 20px
  h4
    font-size 13px
    float left
    width 85%
    white-space nowrap
    overflow hidden
    text-overflow ellipsis
  .greyFont, .kmcontent
    color $cf-gray5
    word-break break-all
  .result_list
    padding 8px 5px
    position relative
    overflow hidden
    &:first-child
      background-color $list-active
    &:hover
      background-color $list-active
      cursor pointer
    .kmtitle
      height 20px
      line-height 20px
      .km-type
        font-size 14px
        float right
      .operate
        color $c-main
        position absolute
        top 8px
        right 2px
        height 20px
        line-height 20px
        background-color $list-active
        display none
        span
          margin-right 10px
          cursor pointer
    .km-text-hide
      z-index -1
      position absolute
      visibility hidden
      opacity 0
    .open-text
      position absolute
      bottom 5px
      right 6px
      padding 0 5px
      text-align center
      height 20px
      line-height 20px
      background-color $list-active
      cursor pointer
      color $c-main
      display none
  .result_list:hover .operate
    display block
.tree_container .km-tree
  overflow inherit
.btn
  cursor pointer
  margin 20px auto 0
  width 94px
  color $cf-white
  text-align center
  line-height 30px
  height 30px
  border-radius 5px
  .icon-shuaxin
    display inline-block
    font-size 12px
    span
      font-size 12px
      float right
      padding-left 5px
.km_container
  padding 0px 10px 0
.kmlayout
  transition transform 0.35s
  box-shadow 0 3px 6px rgba(0, 0, 0, 0.3)
  animation kmMovelayout 0.4s
  @keyframes kmMovelayout
    0%
      transform translateX(800px)
    100%
      transform translateX(0)
.kmlayin
  transform translateX(800px)
  transition transform 0.35s
.km_baseinfo_preview
  position fixed
  z-index 1998
  right 0px
  top 95px
  bottom 205px
  background $cf-white
  border-left 1px solid #d3d3d3
  overflow-y auto
  overflow-x hidden
  cursor auto
  width 800px
  color $cf-level2
  .km_preview_title
    height 38px
    border-bottom 1px solid #CCCCCC
    .titleText
      font-size 14px
      color #000000
      font-weight 600
      line-height 38px
      margin-left 20px
    .useBtn
      position absolute
      right 100px
      line-height 38px
      cursor pointer
    .useBtn:hover
      color #459ae9
  .km_preview_content
    height calc(100% - 80px)
  .el-icon-close
    position absolute
    width 14px
    font-size 14px
    line-height 38px
    cursor pointer
    z-index 2
    right 30px
    font-weight bold
  .contentTitle
    color #000000
    font-weight 400
    font-size 14px
    margin-bottom 10px
.btn-group
  text-align center
.editor-preview
  overflow-x auto
  max-height calc(100% - 30px)
</style>
<style>
.km-text-limit {
  width: 100%;
  display: -webkit-box;
  /* eslint-disable-next-line*/
  /* autoprefixer: off */
  box-orient: vertical;
  -webkit-box-orient: vertical;
  /* autoprefixer: on */
  -webkit-line-clamp: 3;
  overflow: hidden;
}
</style>
